/**
 * Created by Administrator on 2017/7/22.
 */
import React, { Component } from 'react';
import StorageUtils from '../Storage/StorageUtil'
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    ListView,
    Image,
    TouchableOpacity,
    Platform,
    AsyncStorage,ToastAndroid
} from 'react-native';

class NetUtils extends React.Component{
    /*
     *  get请求
     *  url:请求地址
     *  data:参数
     *  callback:回调函数
     * */
    static getData(url,params,callback){
        let headerResult =  GLOBAL.token;
        console.log('ni ma bi :' + headerResult)
        if (params) {
            let paramsArray = [];
            //拼接参数
            Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
            if (url.search(/\?/) === -1) {
                url += '?' + paramsArray.join('&')
            } else {
                url += '&' + paramsArray.join('&')
            }
        }
        console.log(url)
        //fetch请求
        fetch(url,{
            method: 'GET',
            headers:{
                'ww-token': GLOBAL.token
            }
        })
            .then((response) => {
                console.log(response)
                    if(JSON.parse(response._bodyInit).code==200){
                        console.log('mb'+JSON.parse(response._bodyInit).code)
                        callback(JSON.parse(response._bodyInit))
                    }else{
                        ToastAndroid.show(JSON.parse(response._bodyInit).msg,ToastAndroid.SHORT)
                    }
            }).done();
    }
    /*
     *  post请求
     *  url:请求地址
     *  data:参数
     *  callback:回调函数
     * */
    static post(url,params,headers,callback){
        //fetch请求
        console.log(JSON.stringify(params)+','+url)
        fetch(url,{
            method: 'POST',
            body:params
        })
            .then((response) => {
                console.log(JSON.stringify(response))
                if(JSON.parse(response._bodyInit).code==200){
                    console.log(JSON.stringify(response._bodyInit))
                    callback(response._bodyInit)
                    ToastAndroid.show(JSON.parse(response._bodyInit).msg,ToastAndroid.SHORT)
                }else{
                    ToastAndroid.show(JSON.parse(response._bodyInit).msg,ToastAndroid.SHORT)
                }

            }).done();
    }


    static _getUserToken(){
        StorageUtils._load('loginresult',(params)=>{
            if(params == null){
                return ''
            }else {
                console.log('bbb:'+params.data['ww-token'])
                return params.data['ww-token']
            }
        })

    }


}

module.exports = NetUtils;